package com.cx.java;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtils {
	
	private static JdbcUtils ju = null;
	
	
	private JdbcUtils() {
		
	}
	
	public static synchronized JdbcUtils  getInstance() {
		if(ju == null){
			ju = new JdbcUtils();
		}
		return ju;
	}
	
	

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private Connection getConnection() {
		// 加载数据库驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/daydayup?useUnicode=true&characterEncoding=utf8", "root", "961003");
			return connection;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		// 通过DriverManager获取数据库连接
		catch (SQLException e) {
			e.printStackTrace();
		}
		return null;

	}

	public <T> List<T> executeQuery(Class<T> t, String sql) {
		Connection connection = getConnection();
		List<T> tList = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = connection.createStatement();
			rs = stmt.executeQuery(sql);
			ResultSetMetaData rsm = rs.getMetaData();
			int count = rsm.getColumnCount();
			tList = new ArrayList<T>();
			while(rs.next()) {
				T obj = t.newInstance();
				Field[] fields = t.getDeclaredFields();
				
				
				for(int i = 1; i <= count; i++) {
					String columnName = rsm.getColumnName(i);
					Object value = rs.getObject(columnName);
					for(Field f:fields) {
						if(f.getName().equalsIgnoreCase(columnName)) {
							f.setAccessible(true);
							f.set(obj, value);
							break;
						}
					}
				}
				tList.add(obj);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeResources(rs);
			closeResources(stmt);
			closeResources(connection);
		}
		return tList;
	}	
	
	
	public int executeUpdate(String sql) {
		Connection connection = getConnection();
		Statement stmt = null;
		int resultCount = 0;
		try {
			stmt = connection.createStatement();
			resultCount = stmt.executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeResources(stmt);
			closeResources(connection);
		}
		
		return resultCount;
	}
	
	
	public void closeResources(AutoCloseable resource) {
		if(null != resource) {
			try {
				resource.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
